import React, { PureComponent } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Modal, Select, Input, message, Divider } from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import StandardTable from '@/components/StandardTable';
import DictCode from '@/pages/components/DictCode';
import LineWrap from '../../components/LineWrap'; // td溢出折行组件
import HOCSelect from '@/components/AntDesign/Select';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const { confirm } = Modal;

@connect(({ empIntegratedquery, loading }) => ({
  empIntegratedquery,
  loading: loading.models.empIntegratedquery,
}))
@Form.create()
class EmpInfor extends PureComponent {
  state = {
    visible: false,
    confirmLoading: false,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'empIntegratedquery/getDic',
      payload: ['MSGTYPE', 'CONSULT_WAY', 'CONSULT_STATUS'],
    });
  }

  jumpRouting = (targetRouter, id) => {
    const { jumpRouting } = this.props;
    jumpRouting(targetRouter, id);
  };

  add = () => {
    this.setState({ visible: true });
    const { dispatch, certNo } = this.props;
    // 咨询记录新增客户名称下拉
    dispatch({
      type: 'empIntegratedquery/getEmpNameLis',
      payload: {
        certNo,
      },
    });
    dispatch({
      type: 'empIntegratedquery/queryConsultRcrdHis',
      payload: {
        certNo,
      },
    });
  };

  close = () => {
    this.setState({ visible: false });
  };

  empData = e => {
    const {
      empIntegratedquery: { empNameList },
    } = this.props;
    if (!empNameList) return;
    const arr = empNameList.filter(item => item.sendId === e);
    this.setState({
      areaId: arr[0].areaId,
      custId: arr[0].custId,
      custName: arr[0].custName,
      empName: arr[0].empName,
      certType: arr[0].certType,
      empId: arr[0].empId,
    });
  };

  save = () => {
    const {
      getConsultInfoList = () => {},
      form,
      empIntegratedquery: { consultRcrdHis },
      dispatch,
      certNo,
    } = this.props;
    const { areaId, custId } = this.state;
    form.validateFields((err, values) => {
      if (err) return;
      const data = Object.assign({}, values, { areaId, custId });
      data.type = values.type && values.type.join(',');
      this.setState({ confirmLoading: true });
      if (Object.keys(consultRcrdHis).length && consultRcrdHis.state === 2) {
        dispatch({
          type: 'empIntegratedquery/updateDataList',
          payload: {
            ...data,
            rcrdId: consultRcrdHis.rcrdId,
            vno: consultRcrdHis.vno,
          },
        }).then(() => {
          getConsultInfoList(true);
          this.setState({ confirmLoading: false, visible: false });
        });
      } else {
        const newValue = { ...data };
        const { empId, empName, certType, custName } = this.state;
        newValue.areaId = data.areaId;
        newValue.empCorpName = custName;
        newValue.empName = empName;
        newValue.empCorpId = data.custId;
        newValue.certType = certType;
        newValue.empId = empId;
        newValue.certNo = certNo;
        delete newValue.custName;
        dispatch({
          type: 'searchrecord/addCheckList',
          payload: newValue,
          callback: response => {
            if (response) {
              if (response.data.code === '201') {
                message.error('该姓名已存在，不可以新增！');
              } else if (response.data.code === '202') {
                confirm({
                  title: '提醒',
                  content: '当前人员已存在此项服务，是否确定重复添加?',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  onOk: () => {
                    dispatch({
                      type: 'searchrecord/addList',
                      payload: { ...newValue, custId: data.custId },
                    });
                  },
                  onCancel() {},
                });
              }
            }
            getConsultInfoList(true);
            this.setState({ confirmLoading: false, visible: false });
          },
        });
      }
    });
  };

  render() {
    const { visible, confirmLoading } = this.state;
    const {
      consultInfo,
      addConFlag,
      form: { getFieldDecorator },
      empIntegratedquery: { empNameList, consultRcrdHis },
    } = this.props;
    let dataSource = [];
    if (consultInfo.length > 3) {
      dataSource = consultInfo.splice(0, 3);
    } else {
      dataSource = consultInfo;
    }
    const columns = [
      {
        title: '电话/邮箱',
        dataIndex: 'contactPhone',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: (val, record) => <span>{record.contactPhone || record.contactEmail || '--'}</span>,
      },
      {
        title: '咨询类型',
        dataIndex: 'typeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => <LineWrap content={text} />,
      },
      {
        title: '回复状态',
        dataIndex: 'stateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '时间',
        dataIndex: 'creTime',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: val => (val ? moment(val).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'n11',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', width: 150 } }),
        render: (text, record) => (
          <span
            style={{ color: '#1890FF', cursor: 'pointer' }}
            onClick={() => this.jumpRouting('rcrdId', record.rcrdId)}
          >
            查看
          </span>
        ),
      },
    ];
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 6,
        },
      },
      wrapperCol: {
        xs: {
          span: 17,
        },
      },
    };
    const newDataSource = { list: [] };
    newDataSource.list =
      (dataSource.list &&
        dataSource.list.length &&
        dataSource.list.length > 3 &&
        dataSource.list.splice(3)) ||
      [];
    return (
      <div>
        <Card
          title={<span>咨询记录</span>}
          extra={
            <React.Fragment>
              {addConFlag && <a onClick={this.add}>新增&nbsp;&nbsp;</a>}
              <a onClick={() => this.jumpRouting('rcrdId')}>更多&gt;&gt;</a>
            </React.Fragment>
          }
          id="searchRecordInfor"
        >
          <StandardTable
            selectedRows={[]}
            selectedRowKeys={[]}
            pagination={false}
            data={dataSource}
            rowSelection={null}
            columns={columns}
            rowKey="rcrdId"
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <Modal
          title="新增记录"
          visible={visible}
          okText="保存"
          cancelText="取消"
          onOk={this.save}
          onCancel={this.close}
          destroyOnClose
          confirmLoading={confirmLoading}
        >
          <div>
            <Form>
              <FormItem {...formItemLayout} label={<span>客户名称 </span>}>
                {getFieldDecorator('custId', {
                  rules: [
                    {
                      required: true,
                      message: '请输入客户名称',
                    },
                  ],
                })(
                  <HOCSelect
                    placeholder="请输入关键字检索"
                    style={{ width: '100%' }}
                    showSearch
                    optionFilterProp="children"
                    showArrow={false}
                    onSelect={this.empData}
                  >
                    {empNameList.length &&
                      empNameList.map(item => (
                        <Option key={item.sendId}>{`${item.custName}`}</Option>
                      ))}
                  </HOCSelect>
                )}
              </FormItem>

              <FormItem {...formItemLayout} label={<span>咨询方式</span>}>
                {getFieldDecorator('consultWay', {
                  rules: [
                    {
                      required: true,
                      message: '请填写咨询方式',
                    },
                  ],
                  initialValue: consultRcrdHis.consultWay && `${consultRcrdHis.consultWay}`,
                })(<DictCode dictType="CONSULT_WAY" />)}
              </FormItem>

              <FormItem {...formItemLayout} label="咨询类型">
                {getFieldDecorator('type', {
                  rules: [
                    {
                      required: true,
                      message: '请填写咨询类型',
                    },
                  ],
                  initialValue: consultRcrdHis.typeKeyArr,
                })(<DictCode dictType="MSGTYPE" mode="multiple" />)}
              </FormItem>

              <FormItem {...formItemLayout} label="咨询内容">
                {getFieldDecorator('content', {
                  rules: [
                    {
                      required: true,
                      message: '请填写不超过200字符咨询内容',
                      max: 200,
                    },
                  ],
                  initialValue: consultRcrdHis.content,
                })(<TextArea placeholder="请填写咨询内容" />)}
              </FormItem>

              <Divider />

              <FormItem {...formItemLayout} label="回复状态">
                {getFieldDecorator('state', {
                  rules: [
                    {
                      required: true,
                      message: '请选择回复状态',
                    },
                  ],
                  initialValue: `${consultRcrdHis.state}`,
                })(
                  <DictCode dictType="CONSULT_STATUS" inputType="3" onChange={this.stateOnChange} />
                )}
              </FormItem>

              <FormItem {...formItemLayout} label="回复内容">
                {getFieldDecorator('replyContent', {
                  rules: [
                    {
                      required: true,
                      message: '请输入不超过200字符的回复内容',
                      max: 200,
                    },
                  ],
                  initialValue: consultRcrdHis.replyContent,
                })(<TextArea placeholder="请输入回复内容" />)}
              </FormItem>
            </Form>
          </div>
        </Modal>
      </div>
    );
  }
}

export default EmpInfor;
